<template>
  <div>
    <zm-panel title="产品退货" :visible.sync="value" @change="close">
      <zm-form label-width="100px" :model="form" :rules="rules" ref="form">
        <zm-form-item label="商品退货：">
          <span>实物商品退回，客户退货时确认商品是否有破损</span>
        </zm-form-item>
        <zm-form-item label="" label-width="0px">
          <zm-table-data :data="form.productList" :show-page="false" :border="false" :stripe="false" class="mb20">
            <zm-table-column prop="name" label="商品名称" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{scope.row.name}}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="price" label="销售单价（元）" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{scope.row.price}}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="canBackNum" label="可退数量" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{scope.row.canBackNum}}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="canBackDelivery" label="可退运费" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>{{scope.row.canBackDelivery}}</div>
              </template>
            </zm-table-column>
            <zm-table-column prop="backNum" label="退货数量" fixed="left" min-width="120">
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.backNum" :max="scope.row.canBackNum" placeholder="退货数量" @input.native="backNumChange($event, scope.row.backNum, scope.$index, 'backNum')">
                  <template slot="append">件</template>
                </el-input>
              </template>
            </zm-table-column>
            <zm-table-column prop="backDelivery" label="运费退款" fixed="left" min-width="120">
              <template slot-scope="scope">
                <el-input type="number" v-model="scope.row.backDelivery" :max="scope.row.canBackDelivery" placeholder="运费退款" @input.native="backNumChange($event, scope.row.backDelivery, scope.$index, 'backDelivery')">
                  <template slot="append">元</template>
                </el-input>
              </template>
            </zm-table-column>
            <zm-table-column prop="totalPrice" label="商品退货金额" fixed="left" min-width="120">
              <template slot-scope="scope">
                <div>￥{{(+scope.row.price * +scope.row.backNum + (+scope.row.backDelivery || 0)).toFixed(2)}}</div>
              </template>
            </zm-table-column>
          </zm-table-data>
        </zm-form-item>
        <zm-form-item label="退货说明：" prop="remark">
          <zm-input type="textarea" v-model="form.remark" maxlength="300" :autosize="{ minRows: 4, maxRows: 6}" show-word-limit placeholder="请输入使退货说明，便于审批人员查看" />
        </zm-form-item>
      </zm-form>
      <div slot="footer" class="tr">
        <el-button @click="close">返回</el-button>
        <el-button type="primary" @click="submit">提交审批</el-button>
      </div>
    </zm-panel>
  </div>
</template>

<script>
import panelMixin from '@/mixins/panelMixin'
import saleOrder from '@/api/src/saleOrder'
import approveProcessApis from '@/api/src/approve'
export default {
  components: {},
  mixins: [panelMixin],
  props: {
    obj: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      form: {
        remark: ''
      },
      rules: {
        remark: { required: true, message: '请输入', trigger: 'blur' }
      }
    }
  },
  computed: {

  },
  created () {
    this.getDetail()
  },
  methods: {
    async getDetail () {
      this.form = await saleOrder.getRefund({ orderId: this.obj.id })
      this.form.productList.map(item => {
        if (!item.backNum) {
          this.$set(item, 'backNum', '0')
        }
        if (!item.backDelivery) {
          this.$set(item, 'backDelivery', '0')
        }
      })
    },
    backNumChange (e, val, idx, label) {
      const resNum = this.form.productList.find(item => {
        return +item.backNum > +item.canBackNum
      })

      const resDelivery = this.form.productList.find(item => {
        return +item.backDelivery > +item.canBackDelivery
      })

      if (this.form.productList[idx].backNum === '') {
        this.$set(this.form.productList[idx], 'backNum', 0)
      }
      /* if (this.form.productList[idx].backDelivery === '') {
        this.$set(this.form.productList[idx], 'backDelivery', 0)
      } */
      if (resNum) {
        // this.$message.warning('退货数量不能大于可退数量')
        this.$set(this.form.productList[idx], 'backNum', this.form.productList[idx].canBackNum)
        return false
      }

      if (resDelivery) {
        // this.$message.warning('退货数量不能大于可退数量')
        this.$set(this.form.productList[idx], 'backDelivery', this.form.productList[idx].canBackDelivery)
        return false
      }

      let reg = new RegExp(/^[0-9]\d*$/).test(this.form.productList[idx].backNum)
      let reg1 = new RegExp(/^([1-9][0-9]*|0)(\.[0-9]?[1-9])?$/).test(this.form.productList[idx].backDelivery)
      if (!reg) {
        // this.$message.warning('请输入正整数')
        this.$set(this.form.productList[idx], 'backNum', 0)
      }
      if (!reg1) {
        this.$set(this.form.productList[idx], 'backDelivery', '')
      }
    },
    async submit () {
      let _valid = false
      this.$refs.form.validate(valid => {
        _valid = valid
      })
      if (!_valid) {
        return
      }

      let refundProductList = []
      this.form.productList.forEach((item, index) => {
        this.$set(refundProductList, index, {
          id: item.id,
          name: item.name,
          price: item.price,
          canBackNum: item.canBackNum,
          canBackDelivery: item.canBackDelivery,
          backDelivery: item.backDelivery,
          unBackNum: item.unBackNum,
          refundNum: item.backNum,
          refundAmount: (+item.price * +item.backNum).toFixed(2)
        })
      })
      const params = {
        orderId: this.obj.id,
        remark: this.form.remark,
        refundProductList: refundProductList
      }
      saleOrder.refund(params).then(async result => {
        await approveProcessApis.submit({
          businessId: result.id,
          processType: '6',
          linkName: this.form.orderNo + this.form.customerName
        })
        this.$message.success('操作成功')
        this.close()
      })
    }
  }
}
</script>
